/**
 * 
 */
package com.m7012e.a_remote.commons;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

import com.leoj.utils.Handler;
import com.m7012e.a_remote.communication.Message;

/**
 * @author leoj
 *
 */
public class ARemoteTcpListener extends Thread {
	private ServerSocket _server;
	private ObjectInputStream _input;
	private Handler<Message> _messageAnalyzer;
	
	
	public ARemoteTcpListener(int port, Handler<Message> analyzer) {
		_messageAnalyzer = analyzer;
		try {
			_server = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		while(true){
			try{
				Socket s = _server.accept();
				_input = new ObjectInputStream(s.getInputStream());
				
				while(s.isConnected()){
					Object o = _input.readObject();
					if (o instanceof Message) {
						Message msg = (Message) o;
						_messageAnalyzer.handle(msg);
					}
					s.close();
				}
			} catch (IOException e){
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	public String getAddress() {
		return _server.getInetAddress().getHostAddress();
	}
	public int getPort() {
		return _server.getLocalPort();
	}
	public SocketAddress getSocketAddress() {
		return _server.getLocalSocketAddress();
	}
	
}
